package com.example.mqtt.common.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/5/2 15:14
 **/
@WebFilter("/*")
public class UserInfoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        UserInfo user = new UserInfo();
        user.setUserId(httpRequest.getHeader("X-User-Id"));
        user.setUsername(httpRequest.getHeader("X-User-Name"));

        try {
            UserContext.setCurrentUser(user);
            chain.doFilter(request, response);
        } finally {
            UserContext.clear();
        }
    }
}
